/**
 * 所属节点：盘点分析列表
 * 创建人：zm
 * 创建时间：2024年8月22日
 * 最后修改人：zm
 */
cb.define(process.env.__DOMAINKEY__, ["common/common_VM.Extend.js"], function (common) {
  let GDGY01_dxq_checkdiff_VM_Extend = {
    doAction: function (name, viewModel) {
      if (this[name]) this[name](viewModel);
    },
    init: function (viewModel) {
      const qianzhui = "/gdgy/pc/isv2";
      var tenantID = viewModel.getAppContext().tenant.tenantId;
      var userId = viewModel.getAppContext().user.userId;
	  var warehouseId = "";
      // 数据初始化
      viewModel.on("customInit", function (data) {
        // console.log("[customInit]")
        // 加载全局配置
        // let resConfig = cb.rest.invokeFunction("GDGY01.BaseConfig.baseConfig", {}, function (err, res) {}, viewModel, {
        //   async: false,
        // });
        // debugger;
        // const domainKey = viewModel.getDomainKey();
        // let baseconfiurl = qianzhui + "/gateway/getEnv?domainKey=" + domainKey + "&tenant_id=" + tenantID;
        // const proxy_baseconfig = viewModel.setProxy({
        //   baseconfig: {
        //     url: baseconfiurl,
        //     method: "GET",
        //     options: {
        //       mask: false,
        //     },
        //   },
        // });
        // let resultbaseconfig = proxy_baseconfig.baseconfigSync();
        /**
         * 张明迁移
         */

        //console.log("[加载全局配置]",resConfig)
        // 盘点分析列表--页面初始化
        // console.log('[盘点分析列表]');

        //var selectedData = [];
        viewModel.selectedData = [];
        viewModel.getParams().autoLoad = false;
        var gridModel = viewModel.getGridModel();
        var ccheckCode = viewModel.getParams().checkCode;
        var checkCodeNow = "";
        if (ccheckCode != null && ccheckCode != undefined) {
          checkCodeNow = ccheckCode;
        } else {
          checkCodeNow = "";
        }
        // console.log(checkCodeNow);
        //var orgIDNow = "";
        var locationNameNow = "";
        var statusNow = "";
        var checkStatusNow = "";
        viewModel.pageNow = 1;
        viewModel.pageSizeNow = 10;
        viewModel.on("afterMount", function () {
          viewModel.getCache("FilterViewModel").getParams().filterRows = 3;
          // console.log("aftermount");
          // 获取查询区模型
          const filtervm = viewModel.getCache("FilterViewModel");
          //查询区模型DOM初始化后
          filtervm.on("afterInit", function () {
            // console.log("[afterInit]");
            var reqParams = {
              tenant_id: tenantID,
              userId: userId,
              //org_id: orgIDNow,
              checkCode: checkCodeNow,
              locationname: locationNameNow,
              // productname: productNameNow,
              status: statusNow,
              checkstatus: checkStatusNow,
              // productskuname: productSkuNameNow,
              page: viewModel.pageNow,
              pagesize: viewModel.pageSizeNow,
            };
            pageInfo(viewModel, reqParams, gridModel);

            //检索触发
            viewModel.on("beforeSearch", function (params) {
              // console.log("[beforeSearch]");
              //var orgIDValue = filtervm.get("org_id").getFromModel().getValue();
              var warehouseIdValue = filtervm.get("warehouseId").getFromModel().getValue();
              var checkCodeValue = filtervm.get("checkCode").getFromModel().getValue();
              var locationNameValue = filtervm.get("localtionName").getFromModel().getValue();
              // var productNameValue = filtervm.get('productName').getFromModel().getValue();
              var statusValue = filtervm.get("status").getFromModel().getValue();
              var checkStatusValue = filtervm.get("checkstatus").getFromModel().getValue();
              // var productSkuNameValue = filtervm.get('productskuName').getFromModel().getValue();

              //orgIDNow = orgIDValue === undefined || orgIDValue === null ? "" : orgIDValue;
			  warehouseId = warehouseIdValue === undefined || warehouseIdValue === null ? "" : warehouseIdValue;
              checkCodeNow = checkCodeValue === undefined || checkCodeValue === null ? "" : checkCodeValue;
              locationNameNow = locationNameValue === undefined || locationNameValue === null ? "" : locationNameValue;
              // productNameNow = productNameValue === undefined || productNameValue === null ? "" : productNameValue;
              statusNow = statusValue === undefined || statusValue === null ? "" : statusValue;
              checkStatusNow = checkStatusValue === undefined || checkStatusValue === null ? "" : checkStatusValue;
              // productSkuNameNow = productSkuNameValue === undefined || productSkuNameValue === null ? "" : productSkuNameValue;
              viewModel.pageNow = 1;
              // pageSizeNow = 10;

              var reqParams = {
                tenant_id: tenantID,
                userId: userId,
                //org_id: orgIDNow,
				warehouseId: warehouseId,
                checkCode: checkCodeNow,
                locationname: locationNameNow,
                // productname: productNameNow,
                status: statusNow,
                checkstatus: checkStatusNow,
                // productskuname: productSkuNameNow,
                page: viewModel.pageNow,
                pagesize: viewModel.pageSizeNow,
              };
              pageInfo(viewModel, reqParams, gridModel);
              return false;
            });
          });
        });

        gridModel.on("pageInfoChange", function () {
          //获取当前页码
          var pageIndex = gridModel.getPageIndex();
          //获取当前页条数
          var pageSize = gridModel.getPageSize();
          viewModel.pageNow = pageIndex;
          viewModel.pageSizeNow = pageSize;
          var reqParams = {
            tenant_id: tenantID,
            userId: userId,
            //org_id: orgIDNow,
			warehouseId: warehouseId,
            checkCode: checkCodeNow,
            locationname: locationNameNow,
            // productname: productNameNow,
            status: statusNow,
            checkstatus: checkStatusNow,
            // productskuname: productSkuNameNow,
            page: viewModel.pageNow,
            pagesize: viewModel.pageSizeNow,
          };
          pageInfo(viewModel, reqParams, gridModel);
        });

        function jsonPush(currentRow) {
          var json1 = {};
          json1.id = currentRow.id;
          json1.locationName = currentRow.hasOwnProperty("locationName") === false ? "" : currentRow.locationName;
          json1.locationCode = currentRow.hasOwnProperty("locationCode") === false ? "" : currentRow.locationCode;
          json1.RFIDCode = currentRow.hasOwnProperty("RFIDCode") === false ? "" : currentRow.RFIDCode;
          json1.warehouseCode = currentRow.hasOwnProperty("warehouseCode") === false ? "" : currentRow.warehouseCode;
          json1.warehouseName = currentRow.hasOwnProperty("warehouseName") === false ? "" : currentRow.warehouseName;
          json1.iStatus = 0;
          // json1.warehouseID = currentRow.warehouseID;
          return json1;
        }

        //监听单选
        gridModel.on("afterSelect", function (data) {
          var index = gridModel.getFocusedRowIndex();
          var currentRow = gridModel.getRow(index);

          if (viewModel.selectedData.length === 0) {
            if (currentRow.status === 0 || currentRow.status === "0") {
              viewModel.selectedData.push(jsonPush(currentRow));
            }
          } else {
            var flag = false;
            for (let i in viewModel.selectedData) {
              if (currentRow.id === viewModel.selectedData[i].id) {
                flag = true;
                continue;
              }
            }
            if (!flag) {
              if (currentRow.status === 0 || currentRow.status === "0") {
                viewModel.selectedData.push(jsonPush(currentRow));
              }
            }
          }
        });
        //监听全选
        gridModel.on("afterSelectAll", function (alldata) {
          if (viewModel.selectedData.length === 0) {
            for (let i in alldata) {
              if (alldata[i].status === 0 || alldata[i].status === "0") {
                viewModel.selectedData.push(jsonPush(alldata[i]));
              }
            }
          } else {
            for (let i in alldata) {
              var flag = false;
              for (let j in viewModel.selectedData) {
                if (alldata[i].id === viewModel.selectedData[j].id) {
                  flag = true;
                  continue;
                }
              }
              if (!flag) {
                if (alldata[i].status === 0 || alldata[i].status === "0") {
                  viewModel.selectedData.push(jsonPush(alldata[i]));
                }
              }
            }
          }
        });
        //取消选中
        gridModel.on("afterUnselect", function (rowIndexs) {
          //var index = gridModel.getFocusedRowIndex();
          //console.log(rowIndexs);
          var currentRow = gridModel.getRow(rowIndexs);
          //console.log("unselect------------------------------------------------------------");

          //console.log(index,currentRow);
          if (viewModel.selectedData.length !== 0) {
            for (let i in viewModel.selectedData) {
              if (currentRow.id === viewModel.selectedData[i].id) {
                viewModel.selectedData.splice(i, 1);
                return false;
              }
            }
          }
        });

        //监听取消全选
        gridModel.on("afterUnselectAll", function (alldata) {
          const rowAllDatas = gridModel.getRows();

          if (viewModel.selectedData.length !== 0) {
            for (let i in rowAllDatas) {
              for (let j in viewModel.selectedData) {
                if (rowAllDatas[i].id === viewModel.selectedData[j].id) {
                  viewModel.selectedData.splice(j, 1);
                  continue;
                }
              }
            }
          }
        });

        //监听数据源改变，设置checkbox
        gridModel.on("afterSetDataSource", function () {
          // console.log("afterSetDataSource------------------------------------------------------------");
          const rowAllDatas = gridModel.getRows();
          const checkedIndexs = [];
          if (rowAllDatas.length !== 0 && viewModel.selectedData.length !== 0) {
            for (let j in rowAllDatas) {
              for (let i in viewModel.selectedData) {
                if (rowAllDatas[j].id === viewModel.selectedData[i].id) {
                  //console.log("setcheckbox-----------------------------------");
                  //gridModel.select(j);
                  checkedIndexs.push(j);
                  continue;
                }
              }
            }
            // console.log("checkedIndexs--------------------------------------" + checkedIndexs);
            gridModel.select(checkedIndexs);
          }
        });
      });

      // 页面数据加载
      function pageInfo(viewModel, reqParams, gridModel) {
        // reqParams.myConfig = resConfig.result; //全局配置参数
        // // console.log("[全局配置参数-pageInfo]"+JSON.stringify(reqParams.myConfig))
        // //Idx3.pandian.PandianAnalyList == GDGY01.pandian.PandianAnalyList
        // var ListResult = cb.rest.invokeFunction(
        //   "GDGY01.pandian.PandianAnalyList",
        //   { reqParams: reqParams },
        //   function (err, res) {
        //     // console.log(err, res);
        //   },
        //   viewModel,
        //   { async: false }
        // );
        // // console.log(JSON.stringify(ListResult));
        // const res = JSON.parse(ListResult.result.strResponse);
        // if (res.status === "1" || res.status === 1) {
        //   gridModel.setState("dataSourceMode", "local");
        //   gridModel.setDataSource(res.dataList);
        //   gridModel.setPageInfo({
        //     pageSize: viewModel.pageSizeNow,
        //     pageIndex: viewModel.pageNow,
        //     recordCount: res.totalSize,
        //   });
        // } else {
        //   cb.utils.alert("系统出错!");
        // }

        /**
         * 张明迁移
         */

        let params = reqParams;
        let url_checkdiff =
          qianzhui +
          "/checkstock/GetCheckDiffList?tenant_id=" +
          tenantID +
          "&userId=" +
          params.userId +
          "&org_id=" +
          params.org_id +
          "&warehouseId=" + params.warehouseId +
          "&checkCode=" +
          params.checkCode +
          "&locationname=" +
          params.locationname +
          "&status=" +
          params.status +
          "&checkstatus=" +
          params.checkstatus +
          "&page=" +
          params.page +
          "&pagesize=" +
          params.pagesize;
        const proxy_checkdiff = viewModel.setProxy({
          checkDiff: {
            url: url_checkdiff,
            method: "GET",
            options: {
              mask: false,
            },
          },
        });
        const resultdel = proxy_checkdiff.checkDiffSync({});
        if (resultdel.status === "1" || resultdel.status === 1) {
          gridModel.setState("dataSourceMode", "local");
          gridModel.setDataSource(resultdel.dataList);
          gridModel.setPageInfo({
            pageSize: viewModel.pageSizeNow,
            pageIndex: viewModel.pageNow,
            recordCount: resultdel.totalSize,
          });
        } else {
          cb.utils.alert("系统出错!");
        }
      }

      viewModel.get("button8xh") &&
        viewModel.get("button8xh").on("click", function (data) {
          // 自动处理--单击

          var gridModel = viewModel.getGridModel();
          var tenantID = viewModel.getAppContext().tenant.tenantId;
          var userId = viewModel.getAppContext().user.userId;
          //var selectedData = [];
          viewModel.selectedData = [];
          viewModel.getParams().autoLoad = false;
          var gridModel = viewModel.getGridModel();
          //var orgIDNow = "";
          var checkCodeNow = "";
          var locationNameNow = "";
          var productNameNow = "";
          var statusNow = "";
          var checkStatusNow = "";
          var productSkuNameNow = "";
          var pageNow = viewModel.pageNow;
          var pageSizeNow = viewModel.pageSizeNow;
          // 选中的内容
          const indexArr = gridModel.getSelectedRowIndexes();

          // 已为一致状态的数据和Id集合
          var alreadyfit = 0;
          var alreadyfitId = [];

          var panYinOrder = [];
          var panKuiOrder = [];
          var panyingIdString = "";
          var pankuiIdString = "";

          // 数据选中检测和对一致状态的剔除
          if (indexArr == null || indexArr.length == 0) {
            cb.utils.alert("您未选中任何需要处理的数据行,无法进行自动处理");
          } else {
            for (var i = 0; i <= indexArr.length - 1; i++) {
              const rowData = gridModel.getRow(indexArr[i]);
              var checkstatus = rowData.checkstatus;
              var status = rowData.status;
              // 测试完成后 进行恢复
              if (checkstatus == 1 || status != 0) {
                var alreadyfitIndex = indexArr[i];
                alreadyfit++;
                alreadyfitId.push(alreadyfitIndex);
              }
            }
            // 提示和反选一致状态的数据
            if (alreadyfit > 0) {
              for (var i = 0; i <= alreadyfitId.length - 1; i++) {
                gridModel.unselect(alreadyfitId[i]);
              }
              var warringInfo =
                "您选中了包含一致状态和已经处理的数据，已自动将对应数据取消选中，请重新点击自动处理按钮。";
              cb.utils.alert(warringInfo);
            } else {
              for (var i = 0; i <= indexArr.length - 1; i++) {
                const rowData = gridModel.getRow(indexArr[i]);
                var checkstatus = rowData.checkstatus;
                // 盘亏
                if (checkstatus == 0) {
                  panKuiOrder.push(rowData);
                  //继续进行数据拼接
                  pankuiIdString += rowData.id + ",";
                }
                // 盘盈
                if (checkstatus == 2) {
                  panYinOrder.push(rowData);
                  panyingIdString += rowData.id + ",";
                }
              }
              // console.log(pankuiIdString);
              // console.log(panyingIdString);

              var pankuiResult = "";
              var panyingResult = "";

              // 盘亏处理
              if (pankuiIdString != null && pankuiIdString != "") {
                const reqParams = {
                  lossIdString: pankuiIdString,
                  tenant_id: tenantID,
                };
                // reqParams.myConfig = resConfig.result; //全局配置参数
                // var PanKuiHandleResult = cb.rest.invokeFunction(
                //   "GDGY01.pandian.PanKuiAutoHandle",
                //   { reqParams: reqParams },
                //   function (err, res) {},
                //   viewModel,
                //   { async: false }
                // );
                // // console.log(PanKuiHandleResult);
                // const res = JSON.parse(PanKuiHandleResult.result.strResponse);
                // pankuiResult = "盘亏自动处理：" + res.message;
                // // console.log(PanKuiHandleResult.result);

                /**
                 * 张明迁移
                 */

                const url_PanKuiAutoHandle =
                  qianzhui +
                  "/checkstock/CheckStockAutoCreateOtherOutOrder" +
                  "?tenant_id=" +
                  tenantID +
                  "&lossIdString=" +
                  pankuiIdString;
                const proxy_PanKuiAutoHandle = viewModel.setProxy({
                  PanKuiAutoHandle: {
                    url: url_PanKuiAutoHandle,
                    method: "GET",
                  },
                });
                const result_PanKuiAutoHandle = proxy_PanKuiAutoHandle.PanKuiAutoHandleSync({});
                pankuiResult = "盘亏自动处理：" + result_PanKuiAutoHandle.message;
              }
              // 盘盈处理
              if (panyingIdString != null && panyingIdString != "") {
                const panyingparam = {
                  incomeIdString: panyingIdString,
                  tenant_id: tenantID,
                };
                // // console.log(panyingparam);
                // panyingparam.myConfig = resConfig.result; //全局配置参数
                // var panYingHandleResult = cb.rest.invokeFunction(
                //   "GDGY01.pandian.PanYAutoHandle",
                //   { reqParams: panyingparam },
                //   function (err, res) {},
                //   viewModel,
                //   { async: false }
                // );
                // // console.log(panYingHandleResult);
                // const res = JSON.parse(panYingHandleResult.result.strResponse);
                // panyingResult = "盘盈自动处理：" + res.message;
                // console.log(res);
                /**
                 * 张明迁移
                 */
                const url_PanyingAutoHandle =
                  qianzhui +
                  "/epcother/CheckStockAutoCreateOtherInOrder" +
                  "?tenant_id=" +
                  tenantID +
                  "&incomeIdString=" +
                  panyingparam.incomeIdString;
                const proxy_PanyingAutoHandle = viewModel.setProxy({
                  PanyingAutoHandle: {
                    url: url_PanyingAutoHandle,
                    method: "GET",
                  },
                });
                const result_PanyingAutoHandle = proxy_PanyingAutoHandle.PanyingAutoHandleSync({});
                pankuiResult = "盘亏自动处理：" + result_PanyingAutoHandle.message;
              }

              if (pankuiResult != "" && panyingResult != "") {
                cb.utils.alert(panyingResult + "\n" + pankuiResult);
              } else {
                if (pankuiResult != "") {
                  cb.utils.alert(pankuiResult);
                }
                if (panyingResult != "") {
                  cb.utils.alert(panyingResult);
                }
              }

              var reqParams = {
                //org_id: orgIDNow,
				warehouseId: warehouseId,
                checkCode: checkCodeNow,
                locationname: locationNameNow,
                // productname: productNameNow,
                status: statusNow,
                checkstatus: checkStatusNow,
                // productskuname: productSkuNameNow,
                page: pageNow,
                pagesize: pageSizeNow,
                tenant_id: tenantID,
                userId: userId,
              };
              pageInfo(viewModel, reqParams, gridModel);
            }
          }
        });

      viewModel.get("button8qd") &&
        viewModel.get("button8qd").on("click", function (data) {
          // 返回盘点单列表--单击
          var gridModel = viewModel.getGridModel();
          var gridModelData = gridModel.getData();
          // console.log(gridModelData);
          var flag = true;
          for (var i = 0; i < gridModelData.length; i++) {
            if (gridModelData[i].status == 0) {
              flag = false;
              break;
            }
          }

          let data1 = {
            billtype: "VoucherList", // 单据类型
            billno: "dxq_checkstockList", // 单据号
            params: {
              mode: "browse", // (编辑态edit、新增态add、浏览态browse)
              //传参
            },
          };
          if (flag) {
            //打开一个单据，并在当前页面显示
            cb.loader.runCommandLine("bill", data1, viewModel);
          } else {
            cb.utils.confirm(
              "当前页面存在未处理的数据，是否返回",
              () => {
                cb.loader.runCommandLine("bill", data1, viewModel);
              },
              () => {}
            );
          }
        });

      viewModel.get("button19uk") &&
        viewModel.get("button19uk").on("click", function (data) {
          // 返回按钮--单击
          viewModel.communication({ type: "return", payload: { data: true } });
        });
    },
  };
  try {
    module.exports = GDGY01_dxq_checkdiff_VM_Extend;
  } catch (error) {}
  return GDGY01_dxq_checkdiff_VM_Extend;
});
